package com.zprmb.udzt.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.widget.RemoteViews;

import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageService;
import com.umeng.message.common.UmLog;
import com.umeng.message.entity.UMessage;
import com.zprmb.udzt.MainActivity2;
import com.zprmb.udzt.R;
import com.zprmb.udzt.activity.UpushActivity;
import com.zprmb.udzt.activity.V6LoginActivity3;
import com.zprmb.udzt.util.Helper;
import com.zprmb.udzt.util.MySharePreferenceUtil;
import com.zprmb.udzt.util.NotificationService;

import org.android.agoo.common.AgooConstants;
import org.json.JSONObject;

import java.util.Map;

/**
 * Developer defined push intent service.
 * Remember to call {@link com.umeng.message.PushAgent#setPushIntentServiceClass(Class)}.
 *
 * @author lucas
 */
//完全自定义处理类
public class MyPushIntentService extends UmengMessageService {

    private static final String TAG = MyPushIntentService.class.getName();

    @Override
    public void onMessage(Context context, Intent intent) {
        try {
            //可以通过MESSAGE_BODY取得消息体
            String message = intent.getStringExtra(AgooConstants.MESSAGE_BODY);
            UMessage msg = new UMessage(new JSONObject(message));
            UmLog.d(TAG, "message=" + message);    //消息体
            UmLog.d(TAG, "custom=" + msg.custom);    //自定义消息的内容
            UmLog.d(TAG, "title=" + msg.title);    //通知标题
            UmLog.d(TAG, "text=" + msg.text);    //通知内容
            // code  to handle message here
            // ...

            // 对完全自定义消息的处理方式，点击或者忽略
            boolean isClickOrDismissed = true;
            if (isClickOrDismissed) {
                //完全自定义消息的点击统计
                UTrack.getInstance(getApplicationContext()).trackMsgClick(msg);
            } else {
                //完全自定义消息的忽略统计
                UTrack.getInstance(getApplicationContext()).trackMsgDismissed(msg);
            }
            Intent intentAct = new Intent();

            intentAct.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            String key2 = "";

            for (Map.Entry<String, String> entry : msg.extra.entrySet()) {
                String key = entry.getKey();

                String value = entry.getValue();
                if (key.equals("url")) {

                    intent.putExtra(key, value);
                    key2 = value;
                } else {
                    intent.putExtra(key, value);
                    key2 = value;
                }


            }
            String token = (String) MySharePreferenceUtil.get(context, "mytoken", "");

            if (TextUtils.isEmpty(token)) {
                intentAct.putExtra("url", key2);
                intentAct.setClass(context, V6LoginActivity3.class);

            } else if (token.length() < 6) {
                intentAct.putExtra("url", key2);
                intentAct.setClass(context, V6LoginActivity3.class);
//                showNotification(context, msg, intentAct);//必须要有，不然收不到推送的消息
//                showNotification2(context, msg, intentAct);//必须要有，不然收不到推送的消息
            } else {

                if (TextUtils.isEmpty(key2)) {
                    intentAct.setClass(context, MainActivity2.class);

                } else if (key2.length() < 5) {
                    intentAct.setClass(context, MainActivity2.class);

                } else if (key2.length() > 8) {
                    intentAct.putExtra("url", key2);
                    intentAct.setClass(context, UpushActivity.class);

                } else {
//                    showNotification2();
                    intentAct.putExtra("url", key2);
                    intentAct.setClass(context, UpushActivity.class);
//
                }
//                startActivity(intentAct);

            }
            showNotification(context, msg, intentAct);//必须要有，不然收不到推送的消息


            // 使用完全自定义消息来开启应用服务进程的示例代码
            // 首先需要设置完全自定义消息处理方式
//             mPushAgent.setPushIntentServiceClass(MyPushIntentService.class);
            // code to handle to start/stop service for app process
            JSONObject json = new JSONObject(msg.custom);
            String topic = json.getString("topic");
            UmLog.d(TAG, "topic=" + topic);
            if (topic != null && topic.equals("appName:startService")) {
                // 在友盟portal上新建自定义消息，自定义消息文本如下
                //{"topic":"appName:startService"}
                if (Helper.isServiceRunning(context, NotificationService.class.getName()))
                    return;
                Intent intent1 = new Intent();
                intent1.setClass(context, NotificationService.class);
                context.startService(intent1);
            } else if (topic != null && topic.equals("appName:stopService")) {
                // 在友盟portal上新建自定义消息，自定义消息文本如下
                //{"topic":"appName:stopService"}
                if (!Helper.isServiceRunning(context, NotificationService.class.getName()))
                    return;
                Intent intent1 = new Intent();
                intent1.setClass(context, NotificationService.class);
                context.stopService(intent1);
            }
        } catch (Exception e) {
            UmLog.e(TAG, e.getMessage());
        }


    }

    int requestCode;

    // 通知栏显示当前播放信息，利用通知和 PendingIntent来启动对应的activity
    public void showNotification(Context context, UMessage msg, Intent intent) {
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setAutoCancel(true);
        Notification mNotification = builder.build();
        mNotification.icon = R.drawable.ud_logo;//notification通知栏图标
        mNotification.defaults |= Notification.DEFAULT_SOUND;
        mNotification.defaults |= Notification.DEFAULT_VIBRATE;
        mNotification.tickerText = msg.ticker;
        int requestCode = (int) System.currentTimeMillis();
        //自定义布局
        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification_view);
        contentView.setImageViewResource(R.id.notification_large_icon, R.drawable.ud_logo);
//        UmLog.d(TAG, "message=" + message);    //消息体
//        UmLog.d(TAG, "custom=" + msg.custom);    //自定义消息的内容
//        UmLog.d(TAG, "title=" + msg.title);    //通知标题
//        UmLog.d(TAG, "text=" + msg.text);    //通知内容
//
//        UmLog.d(TAG, "time=" + msg.ticker);    //

        contentView.setTextViewText(R.id.notification_title, msg.title);
        contentView.setTextViewText(R.id.notification_text, msg.text);
        //得到long类型当前时间

        java.sql.Timestamp time = new java.sql.Timestamp(new java.util.Date().getTime());
        System.out.println(time.getHours());//时
        System.out.println(time.getMinutes());//分


     /*   for (int i = 0; i < 1; i++) {
            Log.d("count", count + "");
            new MyPushIntentService().method();
        }*/
        if (time.getMinutes() < 10) {

        } else {
            contentView.setTextViewText(R.id.time, time.getHours() + ":" + time.getMinutes() + "");
        }

        mNotification.contentView = contentView;

   /*     PendingIntent contentIntent = PendingIntent.getActivity(context, count,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);//不是Intent*/
        int c = time.getMinutes() + time.getSeconds();
        int m = requestCode + 1;
        PendingIntent contentIntent = PendingIntent.getActivity(context, requestCode,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);//不是Intent
        //notifcation.flags = Notification.FLAG_NO_CLEAR;// 永久在通知栏里
        mNotification.flags = Notification.FLAG_AUTO_CANCEL;

        //使用自定义下拉视图时，不需要再调用setLatestEventInfo()方法，但是必须定义contentIntent
        mNotification.contentIntent = contentIntent;
//        contentView.setImageViewResource(R.id.notification_small_icon, getSmallIconId(context, msg));   .setContentIntent(contentIntent);
        builder.setContent(contentView)
                .setSmallIcon(R.drawable.ud_logo)
                .setTicker(msg.ticker)

                .setContentIntent(contentIntent)
                .setAutoCancel(true);

        mNotificationManager.notify(m, mNotification);

    }

    public static int count = 0;

    public void method() {

        count++;


    }

}
